package com.zsl.swing.redis.desktop.window.panel;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;

public class ZslImgPanel  extends JPanel {

    private final Image image;

//    private Window parent;

    public ZslImgPanel(Image image, Window parent){
//        this.parent =  parent;
        Objects.requireNonNull(image);
        this.image = image.getScaledInstance(parent.getWidth(),parent.getHeight() * 5/6 ,Image.SCALE_SMOOTH);
    }

    public static ZslImgPanel getInstance(String imgPath, Window c){

        try (
                InputStream in = ZslImgPanel.class.getResourceAsStream(imgPath);
                BufferedReader br = new BufferedReader(new InputStreamReader(Objects.requireNonNull(in), StandardCharsets.UTF_8))
                ){

            String line;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine()) != null){
                sb.append(line);
            }

            byte[] decode = Base64.getDecoder().decode(sb.toString().getBytes(StandardCharsets.UTF_8));
            ByteArrayInputStream bis = new ByteArrayInputStream(decode);

            BufferedImage read = ImageIO.read(bis);
            bis.close();
            return new ZslImgPanel(read,c);
        } catch (IOException e) {
           return new ZslImgPanel(new BufferedImage(c.getWidth(),c.getHeight(), BufferedImage.TYPE_4BYTE_ABGR),c);
        }
    }


    public static void main(String[] args) {
//        InputStream in = ZslImgPanel.class.getResourceAsStream(StaticFields.IPM_PATH);
//
//        Objects.requireNonNull(in);
//        byte[] bytes = new byte[in.available()];
//        in.read(bytes);
//
//        in.close();
//
//        byte[] target = Base64.getEncoder().encode(bytes);
//        String imgBase64 = new String(target, StandardCharsets.UTF_8);
//
//        System.out.println(imgBase64);
//
//        FileOutputStream fos = new FileOutputStream("E:/imp.json");
//        fos.write(imgBase64.getBytes(StandardCharsets.UTF_8));
//
//        fos.flush();
//        fos.close();


    }



    @Override
    public void paintComponent(Graphics g){
        if(Objects.isNull(this.image)){
            super.paintComponent(g);
        }else{
            int x = 0,y = 0;
            g.drawImage(this.image,x,y,this);

        }
    }



}
